package com.hele.sts.action.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hele.sts.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hele.sts.pub.StringUtil;
import com.hele.sts.webwork.PageAction;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.beans.factory.annotation.Autowired;

public class DocumentManagerDivAction
  extends PageAction
{
  static Logger logger = LoggerFactory.getLogger(DocumentManagerDivAction.class);
  public static final String BORROW = "borrow";
  public static final String RETURN = "return";
  public static final String LIST = "list";
  public static final String QUERY = "query";
  public static final String LISTALL = "listall";
  public static final String DISPATCH = "dispatch";
  public static final String UPDATE = "update";
  public static final String EDIT = "edit";
  String action;
  QEkUser qEkUser;
  List qEnterQueueList;
  List qyhznrList;
  String userId;
  String errorInfo;
  String userName;
  String unit;
  String department;
  String certificate;
  String telephone;
  String physicalAddress;
  String ipAddress;
  double discount;
  double blance;
  String qymc;
  String nbxh;
  String zch;
  String[] nbxhs;
  Qyhznr qyhznr;
  String flag;
  boolean noList;
  String cbx_hzjl;
  String cbx_bfcx;
  String djjg;
  String gxdw;
  String[] checkedUser;
  @Autowired
  private XtLogDao xtLogDao;


  public DocumentManagerDivAction()
  {
    this.noList = false;
  }
  
  @Override
  public String execute()
    throws Exception
  {
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    String loginName = (String)session.get("AdminUser.loginName");
    if ((loginName == null) || (loginName.length() < 1))
    {
      setErrorInfo("没有登录或登录超时");
      return "error";
    }
    if ("borrow".equalsIgnoreCase(this.action)) {
      return borrow();
    }
    if ("return".equalsIgnoreCase(this.action)) {
      return ret();
    }
    if ("returnlist".equalsIgnoreCase(this.action)) {
        return returnlist();
      }
    if ("singlereturn".equalsIgnoreCase(this.action)) {//单用户归还
        return singlereturn();
      }
    if ("batchRet".equalsIgnoreCase(this.action)) {//批量用户归还
        return batchReturn();
      }
    if ("listall".equalsIgnoreCase(this.action)) {
      return listAll();
    }
    if ("dispatch".equalsIgnoreCase(this.action))
    {
      logger.debug(this.action + "-----");
      return dispatch();
    }
    if ("edit".equalsIgnoreCase(this.action)) {
      return edit();
    }
    return super.execute();
  }
  
private String batchReturn() {

  ActionContext ctx = ActionContext.getContext();
  Map session = ctx.getSession();
  User adminUser = (User)session.get(("AdminUser"));
	if(checkedUser==null||checkedUser.length==0){
		
	}else{
		for (String userId : checkedUser) {
			QUser quser = QUserDao.load(userId);
			QEkUser bean = QEkUserDao.load(userId);
			this.qEnterQueueList = QEnterQueueDao.load(userId);
			Iterator iterator = this.qEnterQueueList.iterator();
	        while (iterator.hasNext()){
	        	QEnterQueue qBean = (QEnterQueue)iterator.next();
		        QLog qLog = createrQLog(qBean, quser, bean);
	            if (!QLogDao.insert(qLog))
	            {
	              setErrorInfo("保存日志失败");
	              logger.error("保存日志失败");
	              return "error";
	            }
	        }
			QEnterQueueDao.delete(userId);
			
	    	quser.setUserName("");
	        quser.setCxqx("");
	        quser.setDyqx("");
	        quser.setStatus("1");
	        quser.setGhrq(new Date());
	        
	        quser.setCxrq(new Date());
	        quser.setRealName("");
	        quser.setYhsf("");
	        quser.setBz("");
	        quser.setDyfs("0");
	        QUserDao.update(quser);
	        
		}
	}
  xtLogDao.insertLog("业务日志","后管批量归还档案成功",adminUser.getUserId(),adminUser.getUserName(),"成功","用户："+adminUser.getUserId()+" 批量归还",this.getClass().getName());

  return "batch";
}

private String singlereturn() {
  ActionContext ctx = ActionContext.getContext();
  Map session = ctx.getSession();
  User adminUser = (User)session.get(("AdminUser"));
	QUser quser = QUserDao.load(this.userId);
	QEkUser bean = QEkUserDao.load(userId);
	QEnterQueue qBean = QEnterQueueDao.loadByNbxh(this.userId, this.nbxh);
	boolean b = QEnterQueueDao.delete(this.userId, this.nbxh);
    if (!b)
    {
      setErrorInfo("删除失败!");
      return "error";
    }
    
    QLog qLog = createrQLog(qBean, quser, bean);
    if (!QLogDao.insert(qLog))
    {
      setErrorInfo("保存日志失败");
      logger.error("保存日志失败");
      return "error";
    }
  xtLogDao.insertLog("业务日志","后管单笔归还档案成功",adminUser.getUserId(),adminUser.getUserName(),"成功","用户："+adminUser.getUserId()+" 单笔归还"+nbxh,this.getClass().getName());

  errorInfo = "归还成功";
    
    this.qEnterQueueList = QEnterQueueDao.load(this.userId);
    if(qEnterQueueList==null||qEnterQueueList.size()==0){
    	
    	quser.setUserName("");
        quser.setCxqx("");
        quser.setDyqx("");
        quser.setStatus("1");
        quser.setGhrq(new Date());
        
        quser.setCxrq(new Date());
        quser.setRealName("");
        quser.setYhsf("");
        quser.setBz("");
        quser.setDyfs("0");
        if (!QUserDao.update(quser))
        {
          setErrorInfo("更新用户失败!");
          return "error";
        }
        errorInfo = "全部归还成功";
    }
	return "returnlist";
}

private String returnlist() {
	this.qEnterQueueList = QEnterQueueDao.load(this.userId);
	return "returnlist";
}

public String dispatch()
  {
    logger.debug(this.userId + "--------");
    this.qEkUser = QEkUserDao.load(this.userId);
    if (this.qEkUser == null) {
      return "dispatch";
    }
    return "dispatch1";
  }
  
  public String edit()
  {
    logger.debug(this.userId);
    QUser bean = QUserDao.load(this.userId);
    if (bean == null)
    {
      setErrorInfo("用户不存在");
      return "error";
    }
    logger.debug(bean.getStatus() + "--------");
    bean.setStatus("2");
    bean.setCxrq(new Date());
    boolean a = QUserDao.update(bean);
    if (!a)
    {
      setErrorInfo("更新用户状态失败");
      return "error";
    }
    this.qEkUser = createQEkUser();
    boolean b = QEkUserDao.insert(this.qEkUser);
    if (!b)
    {
      setErrorInfo("添加新用户操作失败");
      return "error";
    }
    return "edit";
  }
  
  @Override
  public String getHref()
  {
    String href = "";
    if ((this.userId != null) && (this.userId.length() > 0)) {
      href = href + "&userId=" + this.userId;
    }
    if ((this.qymc != null) && (this.qymc.length() > 0)) {
      href = href + "&qymc=" + this.qymc;
    }
    if ((this.nbxh != null) && (this.nbxh.length() > 0)) {
      href = href + "&nbxh=" + this.nbxh;
    }
    if ((this.zch != null) && (this.zch.length() > 0)) {
      href = href + "&zch=" + this.zch;
    }
    return href;
  }
  
  public String borrow()
  {
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    User adminUser = (User)session.get(("AdminUser"));
    List list = (List)session.get("list");
    logger.debug(this.userId);
    this.qEkUser = QEkUserDao.load(this.userId);
    if (this.qEkUser == null)
    {
      setErrorInfo("请先关联用户!");
      return "error";
    }
    boolean b = true;
    if ((list != null) && (list.size() > 0)) {
      for (Iterator iterator = list.iterator(); iterator.hasNext();)
      {
        QEnterQueue q = (QEnterQueue)iterator.next();
        logger.debug(q.getNbxh());
        b = QEnterQueueDao.delete(this.userId, q.getNbxh());
        if (!b)
        {
          setErrorInfo("删除失败");
          return "error";
        }
      }
    }
    for (int i = 0; (this.nbxhs != null) && (i < this.nbxhs.length); i++)
    {
      this.qyhznr = QyhznrDao.load(this.nbxhs[i]);
      if (this.qyhznr == null) {
        this.qyhznr = QyhznrDao.loadBfTj(this.nbxhs[i]);
      }
      if (b) {}
      b = QEnterQueueDao.insert(this.userId.toString().trim(), this.qyhznr.getNbxh().toString().trim(), this.qyhznr.getZch().toString().trim(), this.qyhznr.getQymc().toString().trim(), this.qyhznr.getDjjg().toString().trim(), this.qyhznr.getQylx().toString().trim());
    }
    if (!b)
    {
      setErrorInfo("添加档案数据失败");
      return "error";
    }
    session.remove("list");
    this.qEnterQueueList = QEnterQueueDao.load(this.userId);
    String nbxhstr = StringUtils.join(nbxhs);
    xtLogDao.insertLog("业务日志","后管用户借阅档案成功",adminUser.getUserId(),adminUser.getUserName(),"成功","用户："+adminUser.getUserId()+" 借阅档案："+nbxhstr+" 信息",this.getClass().getName());

    return "borrow";
  }
  
  public String ret()
  {
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    User adminUser = (User)session.get(("AdminUser"));

    QEkUser bean = QEkUserDao.load(this.userId);
    this.qEnterQueueList = QEnterQueueDao.load(this.userId);
    if (bean != null)
    {
      QUser quser = QUserDao.load(this.userId);
      if ((this.qEnterQueueList != null) && 
        (this.qEnterQueueList.size() > 0))
      {
        Iterator iterator = this.qEnterQueueList.iterator();
        while (iterator.hasNext())
        {
          QEnterQueue qBean = (QEnterQueue)iterator.next();
          if ((qBean == null) || (quser == null))
          {
            logger.error("qBean is null or quser is null");
          }
          else
          {
            QLog qLog = createrQLog(qBean, quser, bean);
            if (!QLogDao.insert(qLog))
            {
              setErrorInfo("保存日志失败");
              logger.error("保存日志失败");
              return "error";
            }
          }
        }
        if (!QEnterQueueDao.delete(this.userId))
        {
          setErrorInfo("删除档案数据失败!");
          logger.error("删除档案数据失败!");
          return "error";
        }
      }
      quser.setUserName("");
      quser.setCxqx("");
      quser.setDyqx("");
      quser.setStatus("1");
      quser.setGhrq(new Date());
      
      quser.setCxrq(new Date());
      quser.setRealName("");
      quser.setYhsf("");
      quser.setBz("");
      quser.setDyfs("0");
      if (!QUserDao.update(quser))
      {
        setErrorInfo("更新用户失败!");
        return "error";
      }
    }
    xtLogDao.insertLog("业务日志","后管归还档案成功",adminUser.getUserId(),adminUser.getUserName(),"成功","用户："+adminUser.getUserId()+" 归还档案",this.getClass().getName());

    return "ret";
  }
  
  public String listAll()
  {
    logger.debug(this.userId + "------------");
    this.qEkUser = QEkUserDao.load(this.userId);
    this.qEnterQueueList = QEnterQueueDao.load(this.userId);
    if ((this.qEkUser == null) && (this.qEnterQueueList.size() > 0))
    {
      logger.debug("why" + this.qEnterQueueList);
      Iterator iterator = this.qEnterQueueList.iterator();
      while (iterator.hasNext())
      {
        QEnterQueue qBean = (QEnterQueue)iterator.next();
        QUser quser = QUserDao.load(this.userId);
        if ((qBean != null) && (quser != null))
        {
          QLog qLog = createrQLog(qBean, quser, this.qEkUser);
          if (!QLogDao.insert(qLog))
          {
            setErrorInfo("保存日志失败");
            return "error";
          }
        }
      }
      if (!QEnterQueueDao.delete(this.userId))
      {
        setErrorInfo("删除档案数据失败!");
        return "error";
      }
    }
    return "listall";
  }
  
  @Override
  public int count()
  {
    if (this.noList) {
      return 0;
    }
    this.cbx_hzjl = (this.cbx_hzjl != null ? "checked" : "");
    this.cbx_bfcx = (this.cbx_bfcx != null ? "checked" : "");
    if (("".equals(this.cbx_bfcx)) && ("".equals(this.cbx_hzjl))) {
        this.cbx_hzjl = "checked";
      }
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    String djjg = (String)session.get("AdminUser.djjg");
    this.djjg = djjg.endsWith("00")?djjg.substring(0, 4):djjg; 
    this.gxdw = (String)session.get("AdminUser.gxdw");
    if(gxdw.endsWith("00")){
    	this.gxdw = gxdw.substring(0,gxdw.length()-2);
    }
    if(gxdw.endsWith("00")){
    	this.gxdw = gxdw.substring(0,gxdw.length()-2);
    }
    if ("checked".equals(this.cbx_hzjl)) {
    	return QyhznrDao.count(this.qymc, this.nbxh, this.zch,this.djjg,this.gxdw);
    }else{
    	return QyhznrDao.countBf(this.qymc, this.nbxh, this.zch,this.djjg,this.gxdw);
    }
    
  }
  
  @Override
  public String list()
  {
    logger.info("cbx_hzjl1=" + this.cbx_hzjl);
//    this.cbx_hzjl = (this.cbx_hzjl != null ? "checked" : "");
//    this.cbx_bfcx = (this.cbx_bfcx != null ? "checked" : "");
//    if (("".equals(this.cbx_bfcx)) && ("".equals(this.cbx_hzjl))) {
//      this.cbx_hzjl = "checked";
//    }
//    logger.info("cbx_hzjl2=" + this.cbx_hzjl);
    ActionContext ctx = ActionContext.getContext();
    Map session = ctx.getSession();
    //String djjg = (String)session.get("AdminUser.djjg");
    //this.djjg = djjg.endsWith("00")?djjg.substring(0, 4):djjg; 
    if (!this.noList) {
      if ("checked".equals(this.cbx_hzjl)) {
        this.qyhznrList = QyhznrDao.load(this.qymc, this.nbxh, this.zch, this.djjg,this.gxdw,
          getPageNo(), getPageSize());
      } else {
        this.qyhznrList = QyhznrDao.loadbf(this.qymc, this.nbxh, this.zch, this.djjg,this.gxdw,
          getPageNo(), getPageSize());
      }
    }
    if (this.userId != null) {
      this.qEnterQueueList = QEnterQueueDao.load(this.userId);
    }
    if ((!this.noList) && 
      (this.qEnterQueueList.size() > 0))
    {
      logger.debug(this.qEnterQueueList.size() + "size");
      Iterator iterator = this.qEnterQueueList.iterator();
      List list = new ArrayList();
      QEnterQueue q = null;
      Qyhznr y = null;
      int i =0;
    //TODO 修正
      for (; iterator.hasNext()&& i < this.qyhznrList.size();)
      {
        q = (QEnterQueue)iterator.next();
        logger.debug(q.getNbxh());
        y = (Qyhznr)this.qyhznrList.get(i);
        logger.debug(y.getNbxh());
        if (q.getNbxh().equals(y.getNbxh())) {
          list.add(q);
        }
        i++;
      }
      session.put("list", list);
    }
    return "list";
  }
  
  QEkUser createQEkUser()
  {
    QEkUser bean = new QEkUser();
    bean.setBlance(this.blance);
    bean.setCertificate(this.certificate);
    bean.setDepartment(this.department);
    bean.setDiscount(this.discount);
    bean.setIpAddress(this.ipAddress);
    bean.setPhysicalAddress(this.physicalAddress);
    bean.setTelephone(this.telephone);
    bean.setUnit(this.unit);
    bean.setUserId(this.userId);
    bean.setUserName(this.userName);
    return bean;
  }
  
  QLog createrQLog(QEnterQueue eBean, QUser qUser, QEkUser bean)
  {
    QLog log = new QLog();
    logger.debug(qUser.getCxrq() + "." + StringUtil.createLogId() + "." + 
      eBean.getNbxh() + "." + eBean.getQymc().trim() + "." + 
      eBean.getUserId() + "." + qUser.getYhlx());
    logger.debug(qUser.getUserName() + "." + bean.getUserName() + "." + 
      eBean.getZch());
    
    log.setCxrq(new Date());
    log.setLogId(StringUtil.createLogId());
    log.setNbxh(eBean.getNbxh().trim());
    log.setQymc(eBean.getQymc().trim());
    log.setUserId(eBean.getUserId().trim());
    log.setUserName(qUser.getUserName().trim());
    log.setUserNameEk(bean.getUserName().trim());
    log.setYhlx(qUser.getYhlx().trim());
    log.setZch(eBean.getZch().trim());
    
    log.setRealName(qUser.getRealName());
    log.setYhsf(qUser.getYhsf());
    log.setBz(qUser.getBz());
    log.setDyfs(qUser.getDyfs());
    return log;
  }
  
  public String getAction()
  {
    return this.action;
  }
  
  public void setAction(String action)
  {
    this.action = action;
  }
  
  public QEkUser getQEkUser()
  {
    return this.qEkUser;
  }
  
  public void setQEkUser(QEkUser qEkUser)
  {
    this.qEkUser = qEkUser;
  }
  
  public List getQEnterQueueList()
  {
    return this.qEnterQueueList;
  }
  
  public void setQEnterQueueList(List qEnterQueueList)
  {
    this.qEnterQueueList = qEnterQueueList;
  }
  
  public String getUserId()
  {
    return this.userId;
  }
  
  public void setUserId(String userId)
  {
    this.userId = userId;
  }
  
  public String getErrorInfo()
  {
    return this.errorInfo;
  }
  
  public void setErrorInfo(String errorInfo)
  {
    this.errorInfo = errorInfo;
  }
  
  public String getUserName()
  {
    return this.userName;
  }
  
  public void setUserName(String userName)
  {
    this.userName = userName;
  }
  
  public String getUnit()
  {
    return this.unit;
  }
  
  public void setUnit(String unit)
  {
    this.unit = unit;
  }
  
  public String getDepartment()
  {
    return this.department;
  }
  
  public void setDepartment(String department)
  {
    this.department = department;
  }
  
  public String getCertificate()
  {
    return this.certificate;
  }
  
  public void setCertificate(String certificate)
  {
    this.certificate = certificate;
  }
  
  public String getTelephone()
  {
    return this.telephone;
  }
  
  public void setTelephone(String telephone)
  {
    this.telephone = telephone;
  }
  
  public String getPhysicalAddress()
  {
    return this.physicalAddress;
  }
  
  public void setPhysicalAddress(String physicalAddress)
  {
    this.physicalAddress = physicalAddress;
  }
  
  public String getIpAddress()
  {
    return this.ipAddress;
  }
  
  public void setIpAddress(String ipAddress)
  {
    this.ipAddress = ipAddress;
  }
  
  public double getDiscount()
  {
    return this.discount;
  }
  
  public void setDiscount(double discount)
  {
    this.discount = discount;
  }
  
  public double getBlance()
  {
    return this.blance;
  }
  
  public void setBlance(double blance)
  {
    this.blance = blance;
  }
  
  public String[] getNbxhs()
  {
    return this.nbxhs;
  }
  
  public void setNbxhs(String[] nbxhs)
  {
    this.nbxhs = nbxhs;
  }
  
  public String getQymc()
  {
    return this.qymc;
  }
  
  public void setQymc(String qymc)
  {
    this.qymc = qymc;
  }
  
  public String getNbxh()
  {
    return this.nbxh;
  }
  
  public void setNbxh(String nbxh)
  {
    this.nbxh = nbxh;
  }
  
  public String getZch()
  {
    return this.zch;
  }
  
  public void setZch(String zch)
  {
    this.zch = zch;
  }
  
  public List getQyhznrList()
  {
    return this.qyhznrList;
  }
  
  public void setQyhznrList(List qyhznrList)
  {
    this.qyhznrList = qyhznrList;
  }
  
  public String getFlag()
  {
    return this.flag;
  }
  
  public void setFlag(String flag)
  {
    this.flag = flag;
  }
  
  public boolean getNoList()
  {
    return this.noList;
  }
  
  public void setNoList(boolean noList)
  {
    this.noList = noList;
  }
  
  public String getCbx_hzjl()
  {
    return this.cbx_hzjl;
  }
  
  public void setCbx_hzjl(String cbx_hzjl)
  {
    this.cbx_hzjl = cbx_hzjl;
  }
  
  public String getCbx_bfcx()
  {
    return this.cbx_bfcx;
  }
  
  public void setCbx_bfcx(String cbx_bfcx)
  {
    this.cbx_bfcx = cbx_bfcx;
  }

	/**
	 * @return the djjg
	 */
	public String getDjjg() {
		return djjg;
	}
	
	/**
	 * @param djjg the djjg to set
	 */
	public void setDjjg(String djjg) {
		this.djjg = djjg;
	}

	/**
	 * @return the checkedUser
	 */
	public String[] getCheckedUser() {
		return checkedUser;
	}

	/**
	 * @param checkedUser the checkedUser to set
	 */
	public void setCheckedUser(String[] checkedUser) {
		this.checkedUser = checkedUser;
	}
	  
}
